<?php

namespace Home\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;


class CounterTable extends AbstractTableGateway {

    protected $table = 'counter';
	

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new Counter());

        $this->initialize();
    }

    
	
	 public function fetchAll(Select $select = null) {
        if (null === $select)
            $select = new Select();
        $select->from($this->table,array('*'));
        $resultSet = $this->selectWith($select);
        $resultSet->buffer();
        return $resultSet;
    }
	public function sumCounter(Select $select = null) {
        if (null === $select)
            $select = new Select();
        $select->from($this->table)->columns(array(new \Zend\Db\Sql\Expression('SUM(`luongtruycap`) as `luongtruycap`')));
        $resultSet = $this->selectWith($select);
        $row = $resultSet->current();
        return $row;
    }
	
	public function updateLuongtruycap($ngay,$thang,$nam)
	{
		$resultSet = $this->select(array('ngay'=>$ngay,'thang'=>$thang,'nam'=>$nam));
    	$row = $resultSet->current();
		$data = array(
			
			'luongtruycap' => ($row->luongtruycap)+1,
			
		);
		$this->update($data,array('ngay'=>$ngay,'thang'=>$thang,'nam'=>$nam));
		
	}
	public function updateLuotxem($ngay,$thang,$nam)
	{
		$resultSet = $this->select(array('ngay'=>$ngay,'thang'=>$thang,'nam'=>$nam));
    	$row = $resultSet->current();
		$data = array(
			
			'soluotxem' => ($row->soluotxem)+1,
			
		);
		$this->update($data,array('ngay'=>$ngay,'thang'=>$thang,'nam'=>$nam));
		
	}
	public function insertCounter($ngay,$thang,$nam)
	{
		$data = array(
			'nam' => $nam,
			'thang' => $thang,
			'ngay' => $ngay,
			'luongtruycap' => 1,
			'soluotxem' => 1,
		);
		$this->insert($data);
		
	}
	
	
	//kiem tra ton tai
	public function check_exists($ngay,$thang,$nam)
	{
		
		$resultSet = $this->select(array('ngay'=>$ngay,'thang'=>$thang,'nam'=>$nam));
    	$row = $resultSet->current();
        if($row)
		{
			
					$data = array(
						'luongtruycap' => ($row->luongtruycap)+1
					);
					$this->update($data, array('id' => $row->id));

		}
		else{
			$data = array(
				'luongtruycap' => 1,
				'ngay' => $ngay,
				'thang' => $thang,
				'nam' => $nam,
			);
			$this->insert($data);
		}
		
	}
	
	
	


}
